// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (c) 2023 Yevhen Babiichuk (DustDFG)

#include <Abracadabra/GameScene.hpp>

#include <DotSort/Game.hpp>

#include <SFML/System/Clock.hpp>

#include <SFML/Graphics/RenderWindow.hpp>

#include <SFML/Window/Event.hpp>
#include <SFML/Window/Keyboard.hpp>

/* Non game stuff */

#include <cstdint>
#include <vector>

#include <SFML/Graphics.hpp>

#include <Abracadabra/VectorTubeSetBuilder.hpp>

#include <iostream> // DEBUG

GameScene::GameScene(sf::RenderWindow* window)
{
	/* Non game stuff */
	std::vector<std::vector<uint8_t>> ldots = {
		{2, 2, 1, 3},
		{1, 0, 3, 2},
		{3, 0, 1, 0},
		{0, 1},
		{2, 3},
		{},
		{}
	};

	VectorTubeSetBuilder builder(4, 7, ldots);
	this->tubeSet = builder();

	this->view = new View::View(this->tubeSet->tubeSize, this->tubeSet->tubeCount, window);
	this->bg.loadFromFile("./res/test_background_.png");
	this->bgs.setTexture(&this->bg);
	this->bgs.setSize({window->getSize().x, window->getSize().y});
}

GameScene::~GameScene()
{
}

void GameScene::load()
{
}

void GameScene::unload()
{
}

void GameScene::update(sf::Time dt)
{
}

void GameScene::processEvent(sf::Event& event)
{
	if(event.type == sf::Event::MouseButtonPressed)
	{
		std::optional<uint8_t> tubeIndex = this->view->getTubeIndex(event);
		if(tubeIndex)
		{
			this->onTubeClick(tubeIndex.value());
		}
		else
		{
			this->selectedTube = this->selectedTube = std::nullopt;
		}
	}
}

void GameScene::draw(sf::RenderWindow* window) const
{
	window->clear(sf::Color::White);
	updateView();
	window->draw(this->bgs);
	window->draw(*this->view);
	window->display();
}

void GameScene::onTubeClick(uint8_t index)
{
	if(this->selectedTube)
	{
		if(this->selectedTube == index)
		{
			this->selectedTube = std::nullopt;
		}
		else if(this->tubeSet->isPossibleStep(*this->selectedTube, index))
		{
			this->tubeSet->doStep(*this->selectedTube, index);
			this->selectedTube = std::nullopt;
		}
	}
	else
	{
		this->selectedTube = index;
	}
}

void GameScene::updateView() const
{
	for(uint8_t i = 0; i < this->tubeSet->tubeCount; ++i)
	{
		this->view->updateTube(i, this->tubeSet->getTube(i));
	}
}
